package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Problem;
import dao.ProblemDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * created by YT
 * description: 获取题目列表页
 * User:lenovo
 * Data:2022-07-24
 * Time:11:39
 */
@WebServlet("/problem")
public class ProblemServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        //尝试获取题目的id,如果能获取到，就是获取博客详情，如果不能获取到，就是获取博客的列表
        String idString = req.getParameter("id");
        if (idString == null || "".equals(idString)) {
            // 没有获取到id，返回博客列表
            List<Problem> problemList = ProblemDAO.findAllProblems();
            String respString = objectMapper.writeValueAsString(problemList);
            resp.getWriter().write(respString);
        } else {
            // 获得到id，返回详情
            Problem problem = ProblemDAO.findProblem(Integer.valueOf(idString));
            problem.setTestCode("");
            String problemString = objectMapper.writeValueAsString(problem);
            resp.getWriter().write(problemString);

        }


    }
}
